package com.example.xd.Util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class jwtUtil {

    @Value("${jwt.secret}")
   private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

//生成token
    public String generateToken(String email) {
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("email", email);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration + 1000))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    //解析token
    public String getUserEmailFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        Object email = claims.get("email");
        if (email != null&&email instanceof String) {
            return (String) email;
        }
        System.out.println("email为空或者格式不对");
        return null;
    }

    //验证token是否有效
    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        }catch (Exception e) {
            e.printStackTrace(); // 打印详细异常信息
            return false;
        }
    }

}
